/**
 * 改进的装备服务 - 使用新的配置系统
 * 展示如何用新的配置管理器替代复杂的配置查询逻辑
 */

import { DataEquip, DataSkill } from "../shared/face/index";
import { ModernBaseService } from "./base/ModernBaseService";
import { configManager } from "../config/ConfigManager";
import { SkillConfig } from "../config/types/ConfigTypes";
import { DIContainer } from "../infrastructure/di";

export class ImprovedEquipService extends ModernBaseService {
    
    constructor(container?: DIContainer) {
        super(container);
    }
    
    protected async onInit(): Promise<void> {
        // 确保配置管理器已初始化
        await configManager.initialize();
        this.log('ImprovedEquipService initialized with new config system');
    }
    
    /**
     * 获取装备可附魔的技能列表 - 新的简化实现
     * 对比原来的 EquipService.getEnchantableSkills 方法，这个实现更清晰简单
     */
    getEnchantableSkills(equip: DataEquip, playerLevel: number = 1): DataSkill[] {
        try {
            // 使用新的配置管理器，一行代码搞定
            const skillConfigs = configManager.getEnchantableSkills(
                equip.sys,
                equip.type, 
                equip.job,
                equip.solt_type,
                playerLevel
            );
            
            // 过滤掉装备已有的技能
            const existingSkillIds = new Set(equip.skill.map(s => s.skillId));
            const availableSkills = skillConfigs.filter(skill => 
                !existingSkillIds.has(skill.skillId)
            );
            
            // 转换为现有的DataSkill格式
            return availableSkills.map(this.convertSkillConfigToDataSkill);
            
        } catch (error) {
            this.log(`Failed to get enchantable skills: ${(error as any).message}`, 'error');
            return [];
        }
    }
    
    /**
     * 随机选择一个附魔技能
     */
    selectRandomEnchantSkill(equip: DataEquip, playerLevel: number = 1): DataSkill | null {
        try {
            const skillConfig = configManager.selectRandomEnchantSkill(
                equip.sys,
                equip.type,
                equip.job, 
                equip.solt_type,
                playerLevel
            );
            
            if (!skillConfig) {
                this.log('No enchantable skills available for equipment', 'warn');
                return null;
            }
            
            // 检查装备是否已有此技能
            const existingSkillIds = new Set(equip.skill.map(s => s.skillId));
            if (existingSkillIds.has(skillConfig.skillId)) {
                this.log('Selected skill already exists on equipment', 'warn');
                return null;
            }
            
            return this.convertSkillConfigToDataSkill(skillConfig);
            
        } catch (error) {
            this.log(`Failed to select random enchant skill: ${(error as any).message}`, 'error');
            return null;
        }
    }
    
    /**
     * 执行装备附魔
     */
    async enchantEquipment(equip: DataEquip, playerLevel: number = 1): Promise<{
        success: boolean;
        message: string;
        addedSkill?: DataSkill;
        successRate?: number;
    }> {
        try {
            // 计算附魔成功率
            const successRate = this.calculateEnchantSuccessRate(equip);
            
            // 随机判定是否成功
            const isSuccess = Math.random() < successRate;
            
            if (!isSuccess) {
                return {
                    success: false,
                    message: '附魔失败',
                    successRate
                };
            }
            
            // 选择随机技能
            const selectedSkill = this.selectRandomEnchantSkill(equip, playerLevel);
            
            if (!selectedSkill) {
                return {
                    success: false,
                    message: '没有可附魔的技能',
                    successRate
                };
            }
            
            // 添加技能到装备
            equip.skill.push(selectedSkill);
            equip.updateTime = Date.now();
            
            this.log(`Equipment enchanted successfully: ${selectedSkill.reName || selectedSkill.skillId}`);
            
            return {
                success: true,
                message: `成功附魔技能：${selectedSkill.reName || selectedSkill.skillId}`,
                addedSkill: selectedSkill,
                successRate
            };
            
        } catch (error) {
            return {
                success: false,
                message: `附魔过程出错：${(error as any).message}`
            };
        }
    }
    
    /**
     * 计算附魔成功率
     */
    private calculateEnchantSuccessRate(equip: DataEquip): number {
        const currentSkillCount = equip.skill.length;
        
        // 基础成功率：100%（无技能时）
        if (currentSkillCount === 0) {
            return 1.0;
        }
        
        // 每个技能降低15%成功率
        const successRate = Math.max(0.1, 1.0 - (currentSkillCount * 0.15));
        return successRate;
    }
    
    /**
     * 获取装备的固有技能（创建装备时自带的技能）
     */
    getInherentSkills(equipmentTemplateId: string): DataSkill[] {
        try {
            const skillConfigs = configManager.getInherentSkills(equipmentTemplateId);
            return skillConfigs.map(this.convertSkillConfigToDataSkill);
        } catch (error) {
            this.log(`Failed to get inherent skills: ${(error as any).message}`, 'error');
            return [];
        }
    }
    
    /**
     * 根据模板创建装备实例（包含固有技能）
     */
    async createEquipmentFromTemplate(templateId: string, quality?: number): Promise<DataEquip | null> {
        try {
            const template = configManager.getEquipmentTemplate(templateId);
            if (!template) {
                this.log(`Equipment template not found: ${templateId}`, 'error');
                return null;
            }
            
            // 创建基础装备数据
            const equip: DataEquip = {
                uuid: this.sdk.tool.common.uuid,
                id: this.sdk.counter.get('装备ID'),
                name: template.name,
                sys: template.sys,
                type: template.type,
                job: template.job,
                solt_type: template.solt,
                quality: quality || this.randomQuality(template.quality),
                emoji: template.emoji,
                icon: template.icon,
                desc: template.desc || '',
                source: template.source || 'system',
                creator: template.creator || 'system',
                
                // 生成属性
                attribute: this.generateAttributes(template.baseAttributes, quality || template.quality.min),
                
                // 添加固有技能
                skill: this.getInherentSkills(templateId),
                
                strengthenLevel: 1,
                count: 1,
                createTime: Date.now(),
                updateTime: Date.now()
            };
            
            this.log(`Created equipment from template: ${template.name}`);
            return equip;
            
        } catch (error) {
            this.log(`Failed to create equipment from template: ${(error as any).message}`, 'error');
            return null;
        }
    }
    
    /**
     * 获取配置统计信息
     */
    getConfigStats(): any {
        return configManager.getStats();
    }
    
    /**
     * 重新加载配置（开发环境用于热更新）
     */
    async reloadConfigs(): Promise<void> {
        await configManager.reload();
        this.log('Equipment configurations reloaded');
    }
    
    // ==================== 私有辅助方法 ====================
    
    /**
     * 将SkillConfig转换为DataSkill格式
     */
    private convertSkillConfigToDataSkill(skillConfig: SkillConfig): DataSkill {
        return {
            skillId: skillConfig.skillId,
            reName: skillConfig.reName,
            desc: skillConfig.desc || '',
            level: skillConfig.level || 1,
            maxLevel: skillConfig.maxLevel || 10,
            // 可以在这里添加更多字段的转换
            ...skillConfig.customData
        };
    }
    
    /**
     * 随机生成装备品质
     */
    private randomQuality(qualityConfig: any): number {
        const { min, max, weights } = qualityConfig;
        
        if (weights && weights.length > 0) {
            // 基于权重随机
            const totalWeight = weights.reduce((sum: number, weight: number) => sum + weight, 0);
            let random = Math.random() * totalWeight;
            
            for (let i = 0; i < weights.length; i++) {
                random -= weights[i];
                if (random <= 0) {
                    return min + i;
                }
            }
        }
        
        // 简单随机
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    
    /**
     * 生成装备属性
     */
    private generateAttributes(attributeConfigs: any[], quality: number): Array<{key: string, val: number}> {
        return attributeConfigs.map(config => {
            const baseValue = Math.floor(Math.random() * (config.max - config.min + 1)) + config.min;
            const qualityBonus = config.qualityMultiplier ? 
                Math.floor(baseValue * (config.qualityMultiplier - 1) * quality) : 0;
            
            return {
                key: config.key,
                val: baseValue + qualityBonus
            };
        });
    }
}

/**
 * 使用示例 - 在现有的EquipService中集成新系统
 */
export class EquipServiceAdapter {
    private improvedService = new ImprovedEquipService();
    
    async init(): Promise<void> {
        await this.improvedService.init();
    }
    
    /**
     * 替代原来复杂的getEnchantableSkills方法
     */
    getEnchantableSkills(equip: DataEquip): any[] {
        // 新实现比原来简单很多！
        return this.improvedService.getEnchantableSkills(equip);
    }
    
    /**
     * 新增：装备附魔功能
     */
    async enchantEquipment(equip: DataEquip): Promise<any> {
        return await this.improvedService.enchantEquipment(equip);
    }
    
    /**
     * 新增：从模板创建装备
     */
    async createEquipmentFromTemplate(templateId: string): Promise<DataEquip | null> {
        return await this.improvedService.createEquipmentFromTemplate(templateId);
    }
}
